<?php




namespace App\Services;


use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Yansongda\LaravelPay\Facades\Pay;

class Alipay
{

    /**
     *
     * @param $order_no
     * @param $price
     * @param string $title
     * @return string
     */
    public function app($order_no, $price, $title = '支付宝订单')
    {
        $info = [
            'out_trade_no' => $order_no,
            'total_amount' => $price,
            'subject' => $title,
        ];
        return Pay::alipay()->app($info)->getBody()->getContents();
    }


    /**
     * @param $order_no
     * @param $price
     * @return array|\Psr\Http\Message\MessageInterface|\Yansongda\Supports\Collection|null
     * @throws \Yansongda\Pay\Exception\ContainerException
     * @throws \Yansongda\Pay\Exception\InvalidParamsException
     * @throws \Yansongda\Pay\Exception\ServiceNotFoundException
     */
    public function refund($order_no, $price)
    {
        return Pay::alipay()->refund([
            'out_trade_no' => $order_no,
            'refund_amount' => $price,
        ]);
    }

    /**
     * 数据回调
     * @return \Psr\Http\Message\ResponseInterface
     * @throws \Yansongda\Pay\Exception\ContainerException
     * @throws \Yansongda\Pay\Exception\InvalidParamsException
     */
    public function back()
    {
        Log::info("进入回调方法");
        $result = Pay::alipay()->callback();
        Log::info($result);
        if ($result['trade_status'] == 'TRADE_SUCCESS') {
            Log::info("回调验签通过");
            $order_no = $result['out_trade_no'];
            $payResult['pay_no'] = $result['trade_no'];
            $payResult['pay_time'] = $result['gmt_payment'];
            $payResult['pay_price'] = $result['total_amount'];
            $payResult['pay_type'] = 1;
            $type = Str::limit($order_no, 1, '');
            /*if ($type == 'C')
                (new MarketRechargeOrder())->payOrder($order_no, $payResult);
            if ($type == 'O')
                (new StoreOrderPayment())->payOrder($order_no, $payResult);*/
            if ($type == 'M')
                (new StoreOrderPayment())->payMainOrder($order_no, $payResult);
        }
        return Pay::alipay()->success();
    }
}
